<template>
  <div class="home-view">
    <van-nav-bar title="客服工作台" fixed placeholder>
      <template #right>
        <van-icon 
          name="replay" 
          size="20" 
          @click="refreshConnection"
          :class="{ 'rotating': isConnecting }"
        />
      </template>
    </van-nav-bar>

    <!-- 连接状态 -->
    <van-notice-bar
      v-if="!isConnected"
      color="#ff6b6b"
      background="#fff5f5"
      :text="connectionStatus"
      left-icon="info-o"
    />

    <!-- 用户列表 -->
    <div class="user-list-container">;
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-empty 
          v-if="userList.length === 0 && isConnected"
          description="暂无在线客户"
          image="network"
        />
        <van-list 
          v-else
          :finished="true"
          finished-text="没有更多了"
        >
          <van-cell
            v-for="user in userList"
            :key="user.userId"
            :title="user.name"
            :label="`用户ID: ${user.userId}`"
            is-link
            @click="goToChat(user)"
            class="user-item"
          >
            <template #icon>
              <van-icon name="contact" size="24" color="#1989fa" />
            </template>
            <template #value>
              <van-badge 
                v-if="getUnreadCount(user.userId) > 0"
                :content="getUnreadCount(user.userId)"
                :max="99"
              />
            </template>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 连接提示 -->
    <van-loading 
      v-if="isConnecting && !isConnected"
      vertical
      size="24px"
      color="#1989fa"
      class="loading-container"
    >
      正在连接服务器...
    </van-loading>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useWebSocketStore } from '../stores/websocket'
import { Toast } from 'vant'

const router = useRouter()
const wsStore = useWebSocketStore()

const isConnecting = ref(false)
const refreshing = ref(false)

// 使用 store 中的数据
const userList = computed(() => wsStore.userList)
const isConnected = computed(() => wsStore.isConnected)

// 连接状态文本
const connectionStatus = computed(() => {
  if (isConnecting.value) {
    return '正在连接服务器...'
  }
  return '未连接到服务器，请检查网络'
})

// 用户连接回调
const handleUserConnected = (userData) => {
  Toast.success({
    message: `${userData.name} 已连接`,
    duration: 2000
  })
}

// 初始化 WebSocket 连接
const initWebSocket = () => {
  isConnecting.value = true
  
  // 注册用户连接回调
  wsStore.registerUserConnectedHandler(handleUserConnected)
  
  wsStore.init()
  
  // 监听连接状态变化
  const checkConnection = setInterval(() => {
    if (wsStore.isConnected) {
      isConnecting.value = false
      clearInterval(checkConnection)
    }
  }, 100)
  
  // 如果已经连接，立即设置状态
  if (wsStore.isConnected) {
    isConnecting.value = false
  }
}

// 刷新连接
const refreshConnection = () => {
  wsStore.disconnect()
  initWebSocket()
  Toast('正在重新连接...')
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  setTimeout(() => {
    refreshing.value = false
    Toast('刷新完成')
  }, 1000)
}

// 跳转到对话页面
const goToChat = (user) => {
  // 清除未读数
  wsStore.clearUnreadCount(user.userId)
  router.push({
    name: 'chat',
    params: {
      userId: user.userId
    },
    query: {
      userName: user.name
    }
  })
}

// 获取未读消息数
const getUnreadCount = (userId) => {
  return wsStore.getUnreadCount(userId)
}

onMounted(() => {
  initWebSocket()
})
</script>

<style scoped>
.home-view {
  height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.user-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.user-item {
  margin: 8px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.user-item :deep(.van-cell__title) {
  font-weight: 500;
  font-size: 16px;
}

.user-item :deep(.van-cell__label) {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
}

.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
